<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>入组登记 - {{trial.trial_name}}</title>
    <link href="/apps/css/bootstrap.min.css" rel="stylesheet">
    <link href="/apps/css/fontawesome-free-6.4.0-web/css/all.css" rel="stylesheet">
    <script src="/apps/js/baidu-tongji-mtx.js"></script>
</head>
<body>
    <div class="container py-4">
        <div class="row mb-4">
            <div class="col">
                <h2>
                    <a href="/apps/trial" class="text-decoration-none">临床研究支持</a>
                    <i class="bi bi-chevron-right"></i>
                    入组登记
                </h2>
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-body">
                <h3 class="card-title">{{trial.trial_name}}</h3>
                <div class="card-text mb-3">{{{trial.description}}}</div>
                <div class="row">
                    <div class="col-md-4">
                        <small class="text-muted">试验代码：{{trial.trial_code}}</small>
                    </div>
                    <div class="col-md-4">
                        <small class="text-muted">开始日期：{{trial.start_date}}</small>
                    </div>
                    <div class="col-md-4">
                        <small class="text-muted">结束日期：{{#if trial.end_date}}{{trial.end_date}}{{else}}-{{/if}}</small>
                    </div>
                </div>
            </div>
        </div>

        <div class="text-end mb-3">
            <button type="button" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#tipsModal">
                <i class="fas fa-info-circle me-1"></i>入组须知
            </button>
        </div>

        <div class="card">
            <div class="card-body">
                <h4 class="card-title mb-4">入组登记</h4>
                <form action="/apps/trial/entry/{{trial.trial_code}}" method="POST" enctype="multipart/form-data" id="entryForm">
                    <input type="hidden" name="entryInfo" id="entryInfoField">

                    <div class="row g-3">

                        <!-- 入组通知书 -->
                        <div class="col-12">
                            <label class="form-label">《知情同意书》签字并逐页拍照上传</label>
                            <input type="file" class="form-control" id="consent_files" multiple accept="image/*,.pdf">
                            <div class="form-text">必须上传有医生签名的入组通知书</div>
                            <div id="consent_progress" class="mt-2"></div>
                        </div>

                        <div class="col-md-4">
                            <label class="form-label">受试者姓名</label>
                            <input type="text" class="form-control" name="subject_name" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">性别</label>
                            <select class="form-select" name="subject_gender" required>
                                <option value="">请选择</option>
                                <option value="1">男</option>
                                <option value="2">女</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">出生日期</label>
                            <input type="date" class="form-control" name="subject_birth_date" required>
                        </div>

                        <!-- 评分信息 -->
                        <div class="col-md-3">
                            <label class="form-label">ADOS评分</label>
                            <input type="number" class="form-control" name="ados_score" required min="0" max="100" step="any">
                            <div class="form-text">如无评分请填0</div>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">ABC评分</label>
                            <input type="number" class="form-control" name="abc_score" required min="0" max="200" step="any">
                            <div class="form-text">如无评分请填0</div>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">CARS评分</label>
                            <input type="number" class="form-control" name="cars_score" required min="0" max="60" step="any">
                            <div class="form-text">如无评分请填0</div>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">GSRS评分</label>
                            <input type="number" class="form-control" name="gsrs_score" required min="0" max="100" step="any">
                            <div class="form-text">如无评分请填0</div>
                        </div>

                        <!-- ADOS评分 -->
                        <div class="col-md-12">
                            <label class="form-label">ADOS/ABC/CARS/GSRS量表文件</label>
                            <input type="file" class="form-control" id="ados_files" multiple accept="image/*,.pdf">
                            <div class="form-text">可以选择多个文件一起上传，支持图片和PDF格式</div>
                            <div id="ados_progress" class="mt-2"></div>
                        </div>

                        <!-- 监护人信息 -->
                        <div class="col-md-3">
                            <label class="form-label">监护人姓名</label>
                            <input type="text" class="form-control" name="guardian_name" required>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">监护人手机号</label>
                            <input type="tel" class="form-control" name="guardian_phone" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">与受试人关系</label>
                            <input type="text" class="form-control" name="guardian_relation" required>
                        </div>

                        <!-- 收件地址 -->
                        <div class="col-md-3">
                            <label class="form-label">省份</label>
                            <select class="form-select" name="shipping_province" required>
                                <option value="">请选择省份</option>
                            </select>
                        </div>
                        <div class="col-md-9">
                            <label class="form-label">详细地址</label>
                            <input type="text" class="form-control" name="shipping_address_detail" required 
                                   placeholder="请填写城市、区县、街道、小区、门牌号等">
                            <div class="form-text">请填写完整的收件地址（包含城市和区县），确保试验用品能准确送达</div>
                        </div>

                        <!-- 同意条款 -->
                        <div class="col-12 mt-4">
                            <div class="form-check mb-2">
                                <input class="form-check-input consent-check" type="checkbox" id="consentCheck1" name="consentCheck1" required>
                                <label class="form-check-label" for="consentCheck1">
                                    我已了解本试验的目的方法和可能的风险收益
                                </label>
                            </div>
                            <div class="form-check mb-2">
                                <input class="form-check-input consent-check" type="checkbox" id="consentCheck2" name="consentCheck2" required>
                                <label class="form-check-label" for="consentCheck2">
                                    我同意参与本试验并遵从相关自动退组的约定
                                </label>
                            </div>
                            <div class="form-check mb-2">
                                <input class="form-check-input consent-check" type="checkbox" id="consentCheck3" name="consentCheck3" required>
                                <label class="form-check-label" for="consentCheck3">
                                    我同意收集和使用我提供的信息用于本试验研究
                                </label>
                            </div>
                        </div>

                        <div class="col-12">
                            <button type="submit" class="btn btn-primary" id="submitButton" disabled>提交入组登记</button>
                            <a href="/apps/trial/my/trials" class="btn btn-secondary">返回我的试验</a>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="modal fade" id="tipsModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">入组须知</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    {{{trial.entry_tip}}}
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-bs-dismiss="modal">我已了解</button>
                </div>
            </div>
        </div>
    </div>

    <script src="/apps/js/bootstrap.bundle.min.js"></script>
    <script>
        // 从申请信息中初始化表单
        const applyInfo = {{#if applyInfo}}{{{applyInfo}}}{{else}}null{{/if}};

        function initFormFromApplyInfo() {
            if (!applyInfo) return;

            try {
                const info = typeof applyInfo === 'string' ? JSON.parse(applyInfo) : applyInfo;

                // 设置受试者基本信息
                document.querySelector('[name="subject_name"]').value = info.subject_name || '';
                document.querySelector('[name="subject_gender"]').value = info.gender || '';
                document.querySelector('[name="subject_birth_date"]').value = info.birth_date || '';

                // 设置监护人信息
                document.querySelector('[name="guardian_name"]').value = info.contact_name || '';
                document.querySelector('[name="guardian_phone"]').value = info.contact_phone || '';
                document.querySelector('[name="guardian_relation"]').value = info.contact_relation || '';

                // 设置地址信息
                if (info.contact_address) {
                    // 尝试从完整地址中提取省份
                    const provinces = addressData.provinces.map(p => p.name);
                    const province = provinces.find(p => info.contact_address.startsWith(p));
                    if (province) {
                        const provinceSelect = document.querySelector('[name="shipping_province"]');
                        const option = Array.from(provinceSelect.options).find(opt => opt.text === province);
                        if (option) {
                            option.selected = true;
                        }
                    }

                    // 设置详细地址
                    document.querySelector('[name="shipping_address_detail"]').value = info.contact_address;
                }
            } catch (error) {
                console.error('初始化表单失败:', error);
            }
        }

        document.addEventListener('DOMContentLoaded', function() {
            const tipsModal = new bootstrap.Modal(document.getElementById('tipsModal'));
            tipsModal.show();
            /*
            const hasShownTips2 = sessionStorage.getItem('hasShownTips2');
            if (!hasShownTips2) {
                sessionStorage.setItem('hasShownTips2', 'true');
            }
            */

            // 初始化表单
            initFormFromApplyInfo();
        });

        let consentFiles = [];
        let adosFiles = [];

        // 静态省市区数据
        const addressData = {
            provinces: [
                { code: '11', name: '北京市' },
                { code: '12', name: '天津市' },
                { code: '13', name: '河北省' },
                { code: '14', name: '山西省' },
                { code: '15', name: '内蒙古自治区' },
                { code: '21', name: '辽宁省' },
                { code: '22', name: '吉林省' },
                { code: '23', name: '黑龙江省' },
                { code: '31', name: '上海市' },
                { code: '32', name: '江苏省' },
                { code: '33', name: '浙江省' },
                { code: '34', name: '安徽省' },
                { code: '35', name: '福建省' },
                { code: '36', name: '江西省' },
                { code: '37', name: '山东省' },
                { code: '41', name: '河南省' },
                { code: '42', name: '湖北省' },
                { code: '43', name: '湖南省' },
                { code: '44', name: '广东省' },
                { code: '45', name: '广西壮族自治区' },
                { code: '46', name: '海南省' },
                { code: '50', name: '重庆市' },
                { code: '51', name: '四川省' },
                { code: '52', name: '贵州省' },
                { code: '53', name: '云南省' },
                { code: '54', name: '西藏自治区' },
                { code: '61', name: '陕西省' },
                { code: '62', name: '甘肃省' },
                { code: '63', name: '青海省' },
                { code: '64', name: '宁夏回族自治区' },
                { code: '65', name: '新疆维吾尔自治区' }
            ]
        };

        // 初始化省市区选择器
        function initAddressSelectors() {
            const provinceSelect = document.querySelector('[name="shipping_province"]');
            provinceSelect.innerHTML = '<option value="">请选择省份</option>' + 
                addressData.provinces.map(p => `<option value="${p.code}">${p.name}</option>`).join('');
        }

        // 页面加载时初始化地址选择器
        initAddressSelectors();

        // 处理文件上传
        async function handleFileUpload(fileInput, progressDiv) {
            const files = fileInput.files;
            const progressBar = document.getElementById(`${progressDiv}_progress`);
            const targetFiles = getFilesArray(fileInput.id.split('_')[0]);

            progressBar.innerHTML = '<div class="progress"><div class="progress-bar progress-bar-striped progress-bar-animated" style="width: 0%"></div></div>';
            const progressBarFill = progressBar.querySelector('.progress-bar');

            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                const formData = new FormData();
                formData.append('file', file);

                try {
                    progressBarFill.style.width = `${(i / files.length * 100)}%`;
                    progressBarFill.textContent = `上传中 ${i + 1}/${files.length}`;

                    const response = await fetch('https://mall.totembio.cn/api/uploadMtaFile', {
                        method: 'POST',
                        body: formData
                    });

                    const result = await response.json();
                    if (result.status === 200) {
                        targetFiles.push({
                            url: result.data.src,
                            name: file.name
                        });
                    } else {
                        throw new Error(result.message || '上传失败');
                    }
                } catch (error) {
                    progressBar.innerHTML = `<div class="alert alert-danger">文件 ${file.name} ${error.message}</div>`;
                    return;
                }
            }

            if (targetFiles.length > 0) {
                progressBarFill.style.width = '100%';
                progressBarFill.classList.remove('progress-bar-animated');
                progressBarFill.textContent = '上传完成';
                setTimeout(() => {
                    const progressBarDiv = progressBar.querySelector('.progress');
                    if (progressBarDiv) {
                        progressBarDiv.style.display = 'none';
                    }
                }, 1000);
                updateFileList(fileInput.id.split('_')[0]);
            }

            fileInput.value = '';
        }

        // 获取对应的文件数组
        function getFilesArray(fileType) {
            switch(fileType) {
                case 'consent': return consentFiles;
                case 'ados': return adosFiles;
                case 'abc': return abcFiles;
                case 'cars': return carsFiles;
                case 'gsrs': return gsrsFiles;
                case 'subjectId': return subjectIdFiles;
                default: return [];
            }
        }

        // 更新文件列表显示
        function updateFileList(fileType) {
            const progressDiv = document.getElementById(`${fileType}_progress`);
            const filesArray = getFilesArray(fileType);

            let fileList = progressDiv.querySelector('.file-list');
            if (!fileList) {
                fileList = document.createElement('div');
                fileList.className = 'mt-2 file-list';
                progressDiv.appendChild(fileList);
            }

            fileList.innerHTML = filesArray.map((file, index) => `
                <div class="d-flex align-items-center mb-2 bg-light p-2 rounded">
                    <span class="badge bg-light text-dark me-2">${index + 1}</span>
                    <a href="${file.url}" target="_blank" class="me-2">
                        <i class="fas fa-file"></i> ${file.name}
                    </a>
                    <div class="flex-grow-1"></div>
                    <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeFile('${fileType}', ${index})">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            `).join('');

            // 更新文件数量显示
            const statusText = document.createElement('div');
            statusText.className = 'small text-muted mt-2';
            statusText.textContent = `已上传 ${filesArray.length} 个文件`;
            fileList.insertAdjacentElement('afterend', statusText);
        }

        // 删除文件
        function removeFile(fileType, index) {
            const filesArray = getFilesArray(fileType);
            filesArray.splice(index, 1);
            updateFileList(fileType);
        }

        // 为每个文件上传控件添加事件监听器
        ['consent', 'ados', 'abc', 'cars', 'gsrs', 'subjectId'].forEach(fileType => {
            const fileInput = document.getElementById(`${fileType}_files`);
            if (fileInput) {
                fileInput.addEventListener('change', function(e) {
                    handleFileUpload(this, fileType);
                });
            }
        });

        // 处理同意复选框和提交按钮
        const consentChecks = document.querySelectorAll('.consent-check');
        const submitButton = document.getElementById('submitButton');

        function updateSubmitButton() {
            // 检查是否所有复选框都被勾选
            const allChecked = Array.from(consentChecks).every(check => check.checked);
            submitButton.disabled = !allChecked;
        }

        // 为每个复选框添加change事件监听器
        consentChecks.forEach(check => {
            check.addEventListener('change', updateSubmitButton);
        });

        // 确保页面加载时按钮是禁用的
        submitButton.disabled = true;

        document.getElementById('entryForm').addEventListener('submit', function(e) {
            e.preventDefault();

            const formData = new FormData(this);
            const requiredFields = {
                'subject_name': '受试者姓名',
                'subject_gender': '性别',
                'subject_birth_date': '出生日期',
                'guardian_name': '监护人姓名',
                'guardian_phone': '监护人手机号',
                'guardian_relation': '与受试人关系',
                'shipping_province': '省份',
                'shipping_address_detail': '详细地址'
            };

            for (const [field, label] of Object.entries(requiredFields)) {
                const value = formData.get(field);
                if (!value || value.trim() === '') {
                    alert(`请填写${label}`);
                    return;
                }
            }

            // 验证手机号格式
            const phonePattern = /^1[3-9]\d{9}$/;
            if (!phonePattern.test(formData.get('guardian_phone'))) {
                alert('请输入正确的手机号码');
                return;
            }

            // 验证评分值的合理性
            const scores = {
                'ados_score': ['ADOS', 0, 100],
                'abc_score': ['ABC', 0, 200],
                'cars_score': ['CARS', 0, 60],
                'gsrs_score': ['GSRS', 0, 100]
            };

            for (const [field, [name, min, max]] of Object.entries(scores)) {
                const score = parseFloat(formData.get(field));
                if (isNaN(score) || score < min || score > max) {
                    alert(`${name}评分应在${min}到${max}之间`);
                    return;
                }
            }

            // 验证入组通知书是否上传
            if (consentFiles.length === 0) {
                alert('请上传已签署的入组通知书');
                return;
            }

            // 验证量表文件是否上传
            if (adosFiles.length === 0) {
                alert('请上传量表文件');
                return;
            }

            const entryInfo = {
                subject_name: formData.get('subject_name'),
                subject_gender: formData.get('subject_gender'),
                subject_birth_date: formData.get('subject_birth_date'),
                guardian_name: formData.get('guardian_name'),
                guardian_phone: formData.get('guardian_phone'),
                guardian_relation: formData.get('guardian_relation'),
                consent_files: JSON.stringify(consentFiles.map(f => f.url)),
                ados_score: formData.get('ados_score'),
                scale_files: JSON.stringify(adosFiles.map(f => f.url)),
                abc_score: formData.get('abc_score'),
                cars_score: formData.get('cars_score'),
                gsrs_score: formData.get('gsrs_score'),
                shipping_address: {
                    province: document.querySelector('[name="shipping_province"] option:checked').text,
                    detail: formData.get('shipping_address_detail')
                },
                consent_check1: formData.get('consentCheck1') === 'on',
                consent_check2: formData.get('consentCheck2') === 'on',
                consent_check3: formData.get('consentCheck3') === 'on',
            };

            document.getElementById('entryInfoField').value = JSON.stringify(entryInfo);
            this.submit();
        });
    </script>
</body>
</html> 
